<template>
  <el-row>
    <!-- 左 -->
    <el-col :span="4">
      <el-card class="box-card">
        <el-input v-model="input" placeholder="部门名称">
          <template #prefix>
            <el-icon class="el-input__icon">
              <search />
            </el-icon>
          </template>
        </el-input>
        <el-tree :data="_data" :props="defaultProps" @node-click="handleNodeClick" :default-expand-all="true" />
      </el-card>
    </el-col>
    <!-- 右 -->
    <el-col :span="20">
      <!-- 右上搜索按钮组 -->
      <div class="search">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="关键字">
            <el-input v-model="queryParams.keywords" placeholder="用户名/昵称/手机号" clearable />
          </el-form-item>

          <el-form-item label="状态">
            <el-select v-model="form.region" placeholder="全部">
              <el-option label="Zone one" value="shanghai" />
              <el-option label="Zone two" value="beijing" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>

          <el-form-item>
            <el-button :icon="Refresh" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 右下卡片 -->
      <el-card class="box-card">
        <!-- 表头 -->
        <template #header>
          <div class="card-header">
            <div>
              <el-button type="success" :icon="Plus" @click="dialogFormVisible = true">新增</el-button>
              <el-button type="danger" :icon="Delete">删除</el-button>
            </div>

            <div>
              <el-button-group class="ml-4">
                <el-button>导入</el-button>
                <el-button class="icon" :icon="ArrowDown" />
              </el-button-group>
              <el-button class="last-button" :icon="Download">导出</el-button>
            </div>
          </div>

        </template>
        <template #default>
          <div class="card-body">
            <!-- 表单 -->
            <el-table :data="UserList" style="width: 100%">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="编号" width="120" />
              <el-table-column prop="username" label="用户名" width="120" />
              <el-table-column prop="nickname" label="用户昵称" width="120" />
              <el-table-column prop="genderLabel" label="性别" width="120" />
              <el-table-column prop="deptName" label="部门" width="120" />
              <el-table-column prop="mobile" label="手机号" width="120" />
              <!-- <el-table-column prop="status" label="状态" width="120" /> -->
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scoped">
                  <el-switch v-model="scoped.row.status" class="ml-2"
                    style="--el-switch-on-color: #ff4949; --el-switch-off-color: #13ce66" />
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="120" />
              <el-table-column fixed="right" label="操作" width="240">
                <template #default="scope">
                  <el-button link type="primary" size="small" :icon="RefreshLeft">重置密码</el-button>
                  <el-button link type="primary" size="small" :icon="Edit"
                    @click="openDialog(scope.row.id)">编辑</el-button>
                  <el-button link type="primary" size="small" :icon="Delete" @click="open(scope.row.id)">删除</el-button>
                </template>

              </el-table-column>

            </el-table>

            <!-- 分页 -->
            <div class="demo-pagination-block">
              <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
                :page-sizes="[10, 20, 30, 40]" :small="small" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="_total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            </div>
          </div>
        </template>
      </el-card>
    </el-col>

    <el-dialog v-model="dialogFormVisible" title="新增用户" width="600px" append-to-body>
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" :readonly="!!formData.id" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
        </el-form-item>

        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select v-model="formData.deptId" placeholder="请选择所属部门" :data="deptList" filterable check-strictly
            :render-after-expand="false" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择">
            <el-option label="未知" :value="0" />
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改系列 -->
    <el-dialog v-model="updateuserList" title="修改用户" width="600px" append-to-body>
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" :readonly="!!formData.id" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
        </el-form-item>

        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select v-model="formData.deptId" placeholder="请选择所属部门" :data="deptList" filterable check-strictly
            :render-after-expand="false" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择">
            <el-option label="未知" :value="0" />
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="updateuserList = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-row>
</template>

<script setup lang="ts">
import { onBeforeMount, ref, onMounted } from "vue";
import { reactive } from "vue";
import {
  Search,
  Refresh,
  Delete,
  Plus,
  Download,
  ArrowDown,
  RefreshLeft,
  Edit,
} from "@element-plus/icons-vue";

import { getUserPage, getDeptTree, addUser, updateUserStatus, deleteUsers, updateUser, getroles, getUserForm } from "@/api/user"
import { IUserList } from "@/types";
import { ElForm, ElMessage, ElMessageBox } from 'element-plus'

import { UserForm, UserPageVO, UserQuery } from "@/api/user/types";
import { useThrottleFn } from "@vueuse/core";



let UserList = ref<IUserList[]>([]);
let _total = ref<IUserList[]>([]);
let classList = ref<IUserList[]>([]);
onBeforeMount(async () => {
  let {
    data: {
      code,
      data: { list, total },
    },
  } = await getUserPage();


  UserList.value = list;
  _total.value = total
  // console.log(list);
  // console.log(total);

});

let rolesList = ref()
//获取角色列表
onMounted(async () => {
  let data = await getroles()
  console.log('角色列表', data.data.data.list);
  rolesList = data.data.data.list
})







let label = ref('')
let deptList = ref()
onBeforeMount(async () => {

  let data = await getDeptTree()
  // _data = data[0]
  console.log("部门树", data);
  deptList = data.data.data
  label.value = data.data.data[0].label
  classList.value = data.data.data[0].children
  
  
})

// 左
const input = ref("");
interface Tree {
  label: string;
  children?: Tree[];
}

const handleNodeClick = (data: Tree) => {
  console.log(data);
};

// 部门树
let _data = ref([
  {
    label: "有来技术",
    children: [
      {
        label: "研发部门",
      },
      {
        label: "测试部门",
      },
    ],

  },

])
const defaultProps = {
  children: "children",
  label: "label",
};
// 左

// 右
const form = reactive({
  name: "",
  region: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: "",
});
const formInline = reactive({
  user: "",
  region: "",
});


// 分页
const currentPage4 = ref(4);
const pageSize4 = ref(10);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
};
// 右


// 是否删除对话框


const open = (id: string) => {
  ElMessageBox.confirm(
    '您确定要删除吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '算了',
      type: 'warning',
    }
  )
    .then(() => {
      //删除方法
      deleteUsers(id)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      console.log(id);

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败',
      })
    })
}


/**
 * 修改用户
 */

var updateuserList = ref(false)


const userFormRef = ref(ElForm); // 用户表单
//添加系列

const userList = ref<UserPageVO[]>();

const formData = reactive<UserForm>({
  status: 1,
});
//添加用户规则
const rules = reactive({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  roleIds: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});
let dialogFormVisible = ref(false)

let time = Date.now()

const dialog = reactive<DialogOption>({
  visible: false,
});


function openDialog(userId?: number) {
  updateuserList.value = true;
  if (userId) {
    dialog.title = "修改用户";
    console.log(userId);

    getUserForm(userId).then(({ data }) => {
      Object.assign(formData, data.data);
      console.log(data);
    });
  } else {
    formData = null
  }
}



const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      if (userId) {
        console.log(userId, formData);
        updateUser(userId, formData)
          .then(() => {
            ElMessage.success("修改用户成功");
          })
          .finally(() => (updateuserList.value = false));
      } else {
        console.log(formData.roleIds);
        addUser(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            // closeDialog();
            // resetQuery();


          })
          .finally(() => (dialogFormVisible.value = false));
      }
    }
  });
}, 1000);



function delUser(id: any) {
  throw new Error("Function not implemented.");
}


//查询系列
const total = ref(0);
const loading = ref(false);
const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
});

function handleQuery() {
  loading.value = true;
  getUserPage(queryParams)
    .then(({ data }) => {
      UserList.value = data.data.list;
      total.value = data.data.total;
    })
}

// 修改用户状态
function handleStatusChange(row: { [key: string]: any }) {
  const text = row.status === 1 ? "启用" : "停用";
  ElMessageBox.confirm("确认要" + text + row.username + "用户吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      return updateUserStatus(row.id, row.status);
    })
    .then(() => {
      ElMessage.success(text + "成功");
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1;
    });
}


//表单重置
function resetForm() {
  userFormRef.value.resetFields()
  userFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}
</script>

<style scoped lang="less">
.el-row {
  .el-col {
    padding-right: 10px;
    padding-left: 10px;
  }

  .el-col-4 {
    max-width: 16.6666666667%;
    flex: 0 0 16.6666666667%;
  }

  .el-col-20 {
    max-width: 83.3333333333%;
    flex: 0 0 83.3333333333%;

    .search {
      background-color: #fff;
      padding: 18px 0 0 10px;
      margin-bottom: 10px;
      border-radius: 4px;
      box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
    }

    .box-card {
      .card-header {
        display: flex;
        justify-content: space-between;

        .icon {
          padding: 8px;
        }

        .last-button {
          margin-left: 10px;
        }
      }

      .demo-pagination-block {
        padding: 12px;
      }
    }
  }
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>